import paho.mqtt.client as mqtt
import gradio as gr
import paho.mqtt.publish as publish
import paho.mqtt.subscribe as subscribe
import json

def send_msg(message):
    publish.single("llm/ask", message, hostname="120.77.8.146")

def recive_message():
    msg = subscribe.simple("llm/answer", hostname="120.77.8.146")
    #print("%s %s" % (msg.topic, msg.payload))
    msg_json = json.loads(msg.payload)
    return msg_json['message'],  msg_json['history']




with gr.Blocks() as demo:

    chatbot = gr.Chatbot()
    msg = gr.Textbox()
    clear = gr.ClearButton([msg, chatbot])

    def respond(message, chat_history):

        send_msg(json.dumps({'message':message, 'history':chat_history}))
        bot_message, history = recive_message()
        chat_history.append((message, bot_message))
        return "", chat_history

    msg.submit(respond, [msg, chatbot], [msg, chatbot])

demo.launch(server_name='0.0.0.0',server_port=9000)

